﻿using MediatR;
using PublicCommon;
using T_vehicle.Domain;
using T_vehicle.Infrastructure.Impl;
using T_vehicle.Infrastructure.Interfacec;
using T_vehicle.Read.API.Application.Command.TiresUsedCommand;

namespace T_vehicle.Read.API.Application.CommandHandlers.TiresUsedCommandHandlers
{
    public class GetTiresUsedCommandHandlers:IRequestHandler<GetTiresUsedCommand,PageResult<TiresUsed>>
    {
        private readonly ITiresUsedRepository tiresUsedRepository;

        public GetTiresUsedCommandHandlers(ITiresUsedRepository tiresUsedRepository)
        {
            this.tiresUsedRepository = tiresUsedRepository;
        }

        public async Task<PageResult<TiresUsed>> Handle(GetTiresUsedCommand request, CancellationToken cancellationToken)
        {
            var list = tiresUsedRepository.GetAllAsync().Result.Where(x => x.IsDel == false).AsQueryable();

            if (!string.IsNullOrEmpty(request.LicenNumber))
            {
                list = list.Where(x => x.LicenNumber.Contains(request.LicenNumber));
            }

            if (!string.IsNullOrEmpty(request.Tyre))
            {
                list = list.Where(x => x.Tyre.Contains(request.Tyre));
            }

            if (!string.IsNullOrEmpty(request.Specification))
            {
                list = list.Where(x => x.Specification.Contains(request.Specification));
            }

            if (!string.IsNullOrEmpty(request.Users))
            {
                list = list.Where(x => x.Users.Contains(request.Users));
            }

            if (!string.IsNullOrEmpty(Convert.ToString(request.UsersDate)))
            {
                list = list.Where(x => x.UsersDate == request.UsersDate);
            }
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling((totalCount * 1.0) / request.pageSize);
            var res = list.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return  new PageResult<TiresUsed>
            {
                PageCount = pageCount,
                TotalCount = totalCount,
                List = res
            };
        }
    }
}
